const express = require('express');
const router = express.Router();
const multer = require('multer');
const sharp = require('sharp');
const path = require('path');
const fs = require('fs').promises;
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error, validationError } = require('../../utils/response');

// 上传目录配置
const uploadDir = process.env.UPLOAD_DIR || 'public/uploads';
const maxFileSize = parseInt(process.env.MAX_FILE_SIZE) || 5 * 1024 * 1024; // 5MB
const allowedTypes = (process.env.ALLOWED_FILE_TYPES || 'jpg,jpeg,png,gif,webp').split(',');

// 确保上传目录存在
const ensureUploadDir = async () => {
  try {
    await fs.access(uploadDir);
  } catch {
    await fs.mkdir(uploadDir, { recursive: true });
  }
};

// Multer配置
const storage = multer.memoryStorage(); // 使用内存存储，便于图片处理

const fileFilter = (req, file, cb) => {
  const ext = path.extname(file.originalname).toLowerCase().slice(1);
  if (allowedTypes.includes(ext)) {
    cb(null, true);
  } else {
    cb(new Error(`不支持的文件类型，仅支持: ${allowedTypes.join(', ')}`), false);
  }
};

const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: maxFileSize,
    files: 10 // 最多10个文件
  }
});

/**
 * 生成唯一文件名
 */
const generateFileName = (originalName) => {
  const ext = path.extname(originalName);
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 8);
  return `${timestamp}-${random}${ext}`;
};

/**
 * 处理图片（压缩、调整大小）
 */
const processImage = async (buffer, filename) => {
  const outputPath = path.join(uploadDir, filename);
  
  const image = sharp(buffer);
  const metadata = await image.metadata();
  
  // 如果图片宽度超过1920px，则压缩
  if (metadata.width > 1920) {
    await image
      .resize(1920, null, { withoutEnlargement: true })
      .jpeg({ quality: 85 })
      .toFile(outputPath);
  } else {
    await image
      .jpeg({ quality: 90 })
      .toFile(outputPath);
  }
  
  // 获取处理后的图片信息
  const processedMetadata = await sharp(outputPath).metadata();
  
  return {
    width: processedMetadata.width,
    height: processedMetadata.height,
    size: (await fs.stat(outputPath)).size
  };
};

/**
 * 上传单个图片
 * POST /api/upload/image
 */
router.post('/image', authenticateToken, upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return validationError(res, '请选择要上传的图片');
    }

    await ensureUploadDir();

    const user_id = req.user.id;
    const { diary_id } = req.body;

    // 验证日记是否存在且属于当前用户（如果提供了diary_id）
    // 富文本编辑器上传时通常不会传diary_id，这是正常的
    if (diary_id && diary_id !== 'null' && diary_id !== 'undefined' && diary_id.trim() !== '') {
      const diary = await db.Diary.findOne({
        where: { id: diary_id, user_id }
      });
      if (!diary) {
        return error(res, '日记不存在或不属于当前用户', 400);
      }
    }

    const filename = generateFileName(req.file.originalname);
    const filePath = path.join(uploadDir, filename);

    // 处理图片
    const { width, height, size } = await processImage(req.file.buffer, filename);

    // 保存图片信息到数据库
    // 确保diary_id为空时保存为null
    const finalDiaryId = (diary_id && diary_id !== 'null' && diary_id !== 'undefined' && diary_id.trim() !== '') 
      ? parseInt(diary_id) 
      : null;
    
    const image = await db.Image.create({
      user_id,
      diary_id: finalDiaryId,
      filename,
      original_name: req.file.originalname,
      file_path: filePath,
      file_size: size,
      mime_type: req.file.mimetype,
      width,
      height,
      sort_order: 0
    });

    return success(res, {
      id: image.id,
      filename: image.filename,
      original_name: image.original_name,
      url: `/uploads/${image.filename}`,
      width: image.width,
      height: image.height,
      size: image.file_size
    }, '图片上传成功', 200);

  } catch (err) {
    console.error('上传图片错误:', err);
    
    if (err.code === 'LIMIT_FILE_SIZE') {
      return error(res, '文件大小超出限制', 400);
    }
    
    if (err.message.includes('不支持的文件类型')) {
      return error(res, err.message, 400);
    }
    
    return error(res, '图片上传失败', 500);
  }
});

/**
 * 上传头像
 * POST /api/upload/avatar
 */
router.post('/avatar', authenticateToken, upload.single('avatar'), async (req, res) => {
  try {
    if (!req.file) {
      return validationError(res, '请选择要上传的头像');
    }

    await ensureUploadDir();

    const user_id = req.user.id;
    const filename = generateFileName(req.file.originalname);
    
    // 头像特殊处理：裁剪为正方形并压缩
    const avatarDir = path.join(uploadDir, 'avatars');
    try {
      await fs.access(avatarDir);
    } catch {
      await fs.mkdir(avatarDir, { recursive: true });
    }

    const filePath = path.join(avatarDir, filename);
    
    // 处理头像：裁剪为256x256
    await sharp(req.file.buffer)
      .resize(256, 256, { 
        fit: 'cover',
        position: 'center'
      })
      .jpeg({ quality: 90 })
      .toFile(filePath);

    // 获取文件大小
    const stats = await fs.stat(filePath);
    const avatarUrl = `/uploads/avatars/${filename}`;

    // 更新用户头像
    await req.user.update({ avatar: avatarUrl });

    return success(res, {
      url: avatarUrl,
      filename: filename,
      size: stats.size
    }, '头像上传成功', 200);

  } catch (err) {
    console.error('上传头像错误:', err);
    
    if (err.code === 'LIMIT_FILE_SIZE') {
      return error(res, '文件大小超出限制', 400);
    }
    
    if (err.message.includes('不支持的文件类型')) {
      return error(res, err.message, 400);
    }
    
    return error(res, '头像上传失败', 500);
  }
});

/**
 * 批量上传图片
 * POST /api/upload/images
 */
router.post('/images', authenticateToken, upload.array('images', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return validationError(res, '请选择要上传的图片');
    }

    await ensureUploadDir();

    const user_id = req.user.id;
    const { diary_id } = req.body;

    // 验证日记是否存在且属于当前用户（如果提供了diary_id）
    // 富文本编辑器上传时通常不会传diary_id，这是正常的
    if (diary_id && diary_id !== 'null' && diary_id !== 'undefined' && diary_id.trim() !== '') {
      const diary = await db.Diary.findOne({
        where: { id: diary_id, user_id }
      });
      if (!diary) {
        return error(res, '日记不存在或不属于当前用户', 400);
      }
    }

    const uploadedImages = [];
    const errors = [];

    for (let i = 0; i < req.files.length; i++) {
      try {
        const file = req.files[i];
        const filename = generateFileName(file.originalname);
        
        // 处理图片
        const { width, height, size } = await processImage(file.buffer, filename);

        // 保存图片信息到数据库
        // 确保diary_id为空时保存为null
        const finalDiaryId = (diary_id && diary_id !== 'null' && diary_id !== 'undefined' && diary_id.trim() !== '') 
          ? parseInt(diary_id) 
          : null;
        
        const image = await db.Image.create({
          user_id,
          diary_id: finalDiaryId,
          filename,
          original_name: file.originalname,
          file_path: path.join(uploadDir, filename),
          file_size: size,
          mime_type: file.mimetype,
          width,
          height,
          sort_order: i
        });

        uploadedImages.push({
          id: image.id,
          filename: image.filename,
          original_name: image.original_name,
          url: `/uploads/${image.filename}`,
          width: image.width,
          height: image.height,
          size: image.file_size
        });

      } catch (err) {
        errors.push({
          filename: req.files[i].originalname,
          error: err.message
        });
      }
    }

    return success(res, {
      uploaded: uploadedImages,
      errors,
      total_uploaded: uploadedImages.length,
      total_errors: errors.length
    }, '批量上传完成', 200);

  } catch (err) {
    console.error('批量上传图片错误:', err);
    return error(res, '批量上传失败', 500);
  }
});

/**
 * 获取图片列表
 * GET /api/upload/images
 */
router.get('/images', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { diary_id, page = 1, pageSize = 20 } = req.query;

    const where = { user_id };
    if (diary_id) {
      where.diary_id = diary_id;
    }

    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    const { count, rows } = await db.Image.findAndCountAll({
      where,
      attributes: ['id', 'filename', 'original_name', 'file_path', 'file_size', 'width', 'height', 'created_at'],
      offset,
      limit,
      order: [['created_at', 'DESC']]
    });

    const images = rows.map(image => ({
      ...image.toJSON(),
      url: `/uploads/${image.filename}`,
      formatted_size: image.getFormattedSize()
    }));

    return success(res, {
      images,
      pagination: {
        page: parseInt(page),
        pageSize: limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });

  } catch (err) {
    console.error('获取图片列表错误:', err);
    return error(res, '获取图片列表失败', 500);
  }
});

/**
 * 删除图片
 * DELETE /api/upload/images/:id
 */
router.delete('/images/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const image = await db.Image.findOne({
      where: { id, user_id }
    });

    if (!image) {
      return error(res, '图片不存在', 404);
    }

    // 删除物理文件
    try {
      await fs.unlink(image.file_path);
    } catch (err) {
      console.warn('删除物理文件失败:', err.message);
    }

    // 删除数据库记录
    await image.destroy();

    return success(res, null, '图片删除成功');

  } catch (err) {
    console.error('删除图片错误:', err);
    return error(res, '删除图片失败', 500);
  }
});

/**
 * 更新图片排序
 * PUT /api/upload/images/:id/sort
 */
router.put('/images/:id/sort', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { sort_order } = req.body;
    const user_id = req.user.id;

    if (typeof sort_order !== 'number' || sort_order < 0) {
      return validationError(res, '排序值必须是非负整数');
    }

    const image = await db.Image.findOne({
      where: { id, user_id }
    });

    if (!image) {
      return error(res, '图片不存在', 404);
    }

    await image.update({ sort_order });

    return success(res, image, '排序更新成功');

  } catch (err) {
    console.error('更新图片排序错误:', err);
    return error(res, '更新图片排序失败', 500);
  }
});

/**
 * 获取上传配置信息
 * GET /api/upload/config
 */
router.get('/config', (req, res) => {
  return success(res, {
    max_file_size: maxFileSize,
    allowed_types: allowedTypes,
    max_files: 10,
    upload_dir: uploadDir
  });
});

module.exports = router; 